<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.query.account" placeholder="账号" style="width: 200px;" class="filter-item" @keyup.enter.native="filter" />
      <el-input v-model="listQuery.query.name" placeholder="姓名" style="width: 200px;" class="filter-item" @keyup.enter.native="filter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="filter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
    >
      <el-table-column prop="id" align="center" label="ID" width="95" sortable>
        <template v-slot="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column prop="account" label="账号" width="250" sortable>
        <template v-slot="{row}">
          {{ row.account }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="250" sortable>
        <template v-slot="{row}">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="角色">
        <template v-slot="{row}">
          <el-tag v-for="role in row.roles" :key="role.id" style="margin-left: 5px;" type="info">
            {{ role.role.desc }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template v-slot="{row, $index}">
          <el-button type="primary" size="small" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="removeUserProject(row.id, $index)">从项目中移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="listQuery.totalRecords>0" :total="listQuery.totalRecords" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="100px">
        <el-form-item label="项目成员" prop="owner">
          <el-select
            v-if="dialogStatus === 'create'"
            v-model="form.id"
            value-key="id"
            filterable
            placeholder="请选择项目成员"
            @change="userSelectChange"
          >
            <el-option
              v-for="item in notIncludeProjecOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span v-else>{{ form.name }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <el-cascader-panel v-model="form.roles" style="width: 200px;" :options="roles" :props="roleProps" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?update():update()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listByProjectId, removeUserProject, selectUserByNotIncludeProjectId, selectWholeInfoById, update } from '@/api/user'
import { listAllProjectRoles } from '@/api/manage/role'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        totalRecords: 0,
        orders: undefined,
        query: {
          projectId: this.$store.getters.projectId
        }
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      notIncludeProjecOptions: [], // 不包含项目的用户
      roles: [],
      adminRoles: [],
      roleProps: {
        multiple: true, // 支持多选
        value: 'id', // 将数据结构中的id字段绑定到value。value:选择后返回的值
        label: 'desc' // 将数据结构中的name字段绑定到label。label:显示文字
      },
      form: {
        id: undefined,
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入计划名称', trigger: 'change' },
          { max: 50, message: '计划名称 长度不能超过 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      listByProjectId(this.listQuery).then(response => {
        this.list = response.data.list
        this.listQuery.totalRecords = response.data.page.totalRecords
        this.listLoading = false
      })

      // 查询所有项目角色
      listAllProjectRoles().then(response => {
        this.roles = response.data
      })
    },
    filter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: ''
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.selectUserByNotIncludeProjectId()
    },
    handleUpdate(row) {
      this.form = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.selectUserByNotIncludeProjectId()
      selectWholeInfoById({ id: row.id }).then(response => {
        this.adminRoles = []
        response.data.roles.forEach(role => {
          if (role === 1) {
            this.adminRoles.push(1)
          }
        })
        this.form = response.data
      })
    },
    // 项目成员列表改变
    userSelectChange() {
      selectWholeInfoById({ id: this.form.id }).then(response => {
        this.adminRoles = []
        response.data.roles.forEach(role => {
          if (role === 1) {
            this.adminRoles.push(1)
          }
        })
        this.form = response.data
      })
    },
    // 更新用户信息
    update() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 添加，构造 companyList 数据
          if (this.dialogStatus === 'create') {
            let isExistcompany = false
            for (const company of this.form.companyList) {
              if (company.id === this.$store.getters.companyId) {
                let isExistProject = false
                for (const project of company.projectList) {
                  if (project.id === this.$store.getters.projectId) {
                    isExistProject = true
                    break
                  }
                }
                if (!isExistProject) {
                  company.projectList.push({ id: this.$store.getters.projectId })
                }
                isExistcompany = true
                break
              }
            }
            if (!isExistcompany) {
              this.form.companyList.push({
                id: this.$store.getters.companyId,
                projectList: [{ id: this.$store.getters.projectId }]
              })
            }
          }

          // 更新 角色 数据
          this.form.roles.unshift(...this.adminRoles)
          this.form.roles = [...new Set(this.form.roles)] // 去重数组
          this.form.roles = this.form.roles.map(x => +x) // 将角色数组转换为数字数组

          update(this.form).then(response => {
            this.$message({ message: '保存成功!', type: 'success' })
            this.fetchData()
            this.dialogFormVisible = false
          })
        }
      })
    },
    // 将用户从项目中移除
    removeUserProject(userId, index) {
      this.$confirm('是否将此用户从项目中移除?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        removeUserProject(userId, this.$store.getters.projectId).then(response => {
          this.$message({ message: '移除用户成功!', type: 'success' })
          this.list.splice(index, 1)
        })
      }).catch(() => {
      })
    },
    sortChange(column) {
      this.listQuery.orders = [{
        column: column.prop,
        asc: column.order === 'ascending'
      }]
      this.fetchData()
    },
    // 查询不包含项目的用户
    selectUserByNotIncludeProjectId() {
      selectUserByNotIncludeProjectId(this.listQuery.query.projectId).then(response => {
        this.notIncludeProjecOptions = response.data
      })
    }
  }
}
</script>
